package com.baigt.j8.stream;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

import static java.util.stream.Collector.Characteristics.CONCURRENT;

public class StreamCustomCollector3 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Map<String, String> map = Arrays.asList("ricky", "baigt", "weiyi", "ricky1", "baigt1", "weiyi1").parallelStream().collect(new CustomCollector3<String>());
        }
    }
}

class CustomCollector3<E> implements Collector<E, Set<E>, ConcurrentHashMap<E, E>> {

    @Override
    public Supplier<Set<E>> supplier() {
        System.out.println("supplier invoke");
        return HashSet::new;
    }

    @Override
    public BiConsumer<Set<E>, E> accumulator() {
        System.out.println("accumulator invoke ");
        return (sets, e) -> {
            System.out.println(String.format("sets:%s,threadName:%s", sets, Thread.currentThread().getName()));
            sets.add(e);
        };
    }

    @Override
    public BinaryOperator<Set<E>> combiner() {
        System.out.println("combiner");
        return (sets1, sets2) -> {
            sets1.addAll(sets2);
            return sets1;
        };
    }

    @Override
    public Function<Set<E>, ConcurrentHashMap<E, E>> finisher() {
        System.out.println("finisher invoke");
        return (set1) -> {
            ConcurrentHashMap map = new ConcurrentHashMap();
            set1.stream().forEach(set -> {
                map.put(set, set);
            });
            return map;
        };
    }

    @Override
    public Set<Characteristics> characteristics() {
        System.out.println("characterisstics invoke");
        return Collections.unmodifiableSet(EnumSet.of( CONCURRENT));
    }
}
